<template>
  <div class="pdf-viewer-container">
    <h2>PDF文档管理</h2>
    
    <!-- PDF文件列表 -->
    <div class="pdf-list-section">
      <el-card class="pdf-list-card">
        <div slot="header" class="clearfix">
          <span>PDF文件列表</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="fetchPdfList">刷新列表</el-button>
        </div>
        
        <el-table 
          :data="pdfList" 
          style="width: 100%"
          v-loading="loading"
          @row-click="selectPdf"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="fileName" label="文件名" width="300"></el-table-column>
          <el-table-column prop="fileSize" label="文件大小" width="120">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.uploadTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click.stop="downloadPdf(scope.row)">下载</el-button>
              <el-button size="small" type="primary" @click.stop="selectPdf(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
    
    <!-- 下载进度条 -->
    <div class="progress-section" v-if="downloadProgressVisible">
      <el-card>
        <div slot="header" class="clearfix">
          <span>正在下载: {{ downloadingPdf?.fileName }}</span>
        </div>
        <el-progress 
          :percentage="downloadProgress" 
          :status="downloadStatus"
          :stroke-width="20"
          text-inside>
          <span>{{ downloadProgress }}%</span>
        </el-progress>
      </el-card>
    </div>
    
    <!-- PDF查看器 -->
    <div class="pdf-viewer-section" v-if="selectedPdf">
      <el-card class="pdf-viewer-card">
        <div slot="header" class="clearfix">
          <span>正在查看: {{ selectedPdf.fileName }}</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="closePdfViewer">关闭</el-button>
        </div>
        
        <div class="pdf-toolbar">
          <el-button @click="prevPage" :disabled="currentPageNum <= 1">上一页</el-button>
          <el-button @click="nextPage" :disabled="currentPageNum >= totalPages">下一页</el-button>
          <el-button @click="zoomIn">放大</el-button>
          <el-button @click="zoomOut">缩小</el-button>
          <span class="page-info">第 {{ currentPageNum }} 页 / 共 {{ totalPages }} 页</span>
        </div>
        
        <div class="pdf-viewer-content">
          <div 
            class="pdf-container" 
            ref="pdfContainer"
            @scroll="handlePdfScroll">
            <vue-pdf-embed
              :source="pdfSource"
              :page="currentPageNum"
              :style="{ transform: 'scale(' + zoom + ')', transformOrigin: 'top left' }"
              ref="pdfEmbed"
              @rendered="handlePdfRendered"
              @progress="handlePdfProgress"
            />
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getRequest, postRequest } from '../utils/request';
import VuePdfEmbed from 'vue-pdf-embed';

export default {
  name: 'PdfViewer',
  components: {
    VuePdfEmbed
  },
  data() {
    return {
      pdfList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedPdf: null,
      currentPageNum: 1,
      totalPages: 0,
      zoom: 1,
      // 下载进度相关
      downloadProgress: 0,
      downloadProgressVisible: false,
      downloadStatus: null,
      downloadingPdf: null,
      pdfSource: null,
      isScrolling: false
    };
  },
  created() {
    this.fetchPdfList();
  },
  methods: {
    async fetchPdfList() {
      this.loading = true;
      try {
        const response = await postRequest('/pdf/list', {
          page: this.currentPage,
          pageSize: this.pageSize
        });
        this.pdfList = response.data.items;
        this.total = response.data.total;
      } catch (error) {
        this.$message.error('获取PDF列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    tableRowClassName({ row, rowIndex }) {
      if (this.selectedPdf && this.selectedPdf.id === row.id) {
        return 'selected-row';
      }
      return '';
    },
    
    async selectPdf(pdf) {
      console.log('选择PDF文件:', pdf);
      this.selectedPdf = pdf;
      this.currentPageNum = 1;
      this.zoom = 1;
      this.totalPages = 0; // 重置页数
      this.isScrolling = false; // 重置滚动状态
      
      // 显示下载进度条
      this.downloadProgress = 0;
      this.downloadProgressVisible = true;
      this.downloadStatus = null;
      this.downloadingPdf = pdf;
      
      await this.renderPdf();
    },
    
    async renderPdf() {
      if (!this.selectedPdf) return;
      
      try {
        console.log('开始渲染PDF文件:', this.selectedPdf);
        // 获取PDF文件的URL
        const pdfUrl = `/wow/pdf/download/${this.selectedPdf.id}`;
        const accessToken = localStorage.getItem('accessToken');
        console.log('PDF URL:', pdfUrl);
        
        // 使用fetch获取PDF文件并显示进度
        const response = await this.fetchWithProgress(pdfUrl, {
          headers: {
            'access-token': accessToken
          }
        });
        
        console.log('获取PDF响应状态:', response.status);
        if (!response.ok) {
          throw new Error('获取PDF文件失败');
        }
        
        const arrayBuffer = await response.arrayBuffer();
        console.log('获取到的ArrayBuffer大小:', arrayBuffer.byteLength);
        
        // 设置PDF源
        this.pdfSource = { data: arrayBuffer };
        
        // 隐藏下载进度条
        this.downloadProgressVisible = false;
      } catch (error) {
        console.error('加载PDF文件失败:', error);
        this.$message.error('加载PDF文件失败: ' + (error.message || '未知错误'));
        // 隐藏下载进度条
        this.downloadProgressVisible = false;
      }
    },
    
    // 带进度的fetch方法
    async fetchWithProgress(url, options) {
      console.log('开始下载文件:', url);
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        xhr.open(options.method || 'GET', url);
        
        // 设置请求头
        if (options.headers) {
          Object.keys(options.headers).forEach(key => {
            xhr.setRequestHeader(key, options.headers[key]);
          });
        }
        
        // 监听下载进度
        xhr.addEventListener('progress', (event) => {
          if (event.lengthComputable) {
            const percentComplete = Math.round((event.loaded / event.total) * 100);
            this.downloadProgress = percentComplete;
            console.log('下载进度:', percentComplete + '%');
          }
        });
        
        // 监听加载完成
        xhr.addEventListener('load', () => {
          console.log('下载完成，状态码:', xhr.status);
          if (xhr.status >= 200 && xhr.status < 300) {
            this.downloadProgress = 100;
            this.downloadStatus = 'success';
            // 创建Response对象
            const response = new Response(xhr.response, {
              status: xhr.status,
              statusText: xhr.statusText,
              headers: new Headers({
                'content-type': xhr.getResponseHeader('content-type') || 'application/pdf'
              })
            });
            resolve(response);
          } else {
            this.downloadStatus = 'exception';
            reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
          }
        });
        
        // 监听错误
        xhr.addEventListener('error', () => {
          console.error('下载出错');
          this.downloadStatus = 'exception';
          reject(new Error('网络错误'));
        });
        
        // 发送请求
        xhr.responseType = 'arraybuffer';
        xhr.send();
      });
    },
    
    handlePdfRendered() {
      console.log('PDF渲染完成');
      // 使用轮询方式获取页数，确保组件完全初始化
      const checkPageCount = () => {
        if (this.$refs.pdfEmbed) {
          // 尝试多种方式获取页数
          if (this.$refs.pdfEmbed.doc && this.$refs.pdfEmbed.doc.numPages) {
            this.totalPages = this.$refs.pdfEmbed.doc.numPages;
            console.log('通过doc.numPages获取总页数:', this.totalPages);
          } else if (this.$refs.pdfEmbed.pageCount) {
            this.totalPages = this.$refs.pdfEmbed.pageCount;
            console.log('通过pageCount获取总页数:', this.totalPages);
          } else if (this.$refs.pdfEmbed.doc) {
            // 如果doc存在但numPages不存在，可能是异步加载
            console.log('doc存在但页数尚未加载');
            setTimeout(checkPageCount, 200); // 稍后再检查
            return;
          } else {
            console.log('尚未获取到页数信息');
            setTimeout(checkPageCount, 200); // 稍后再检查
            return;
          }
        } else {
          console.log('pdfEmbed引用尚未准备好');
          setTimeout(checkPageCount, 200); // 稍后再检查
          return;
        }
      };
      
      // 开始检查页数
      checkPageCount();
    },
    
    handlePdfProgress(progress) {
      console.log('PDF加载进度:', progress);
    },
    
    handlePdfScroll(event) {
      // 防止在翻页时触发滚动事件
      if (this.isScrolling) return;
      
      const container = event.target;
      const { scrollTop, scrollHeight, clientHeight } = container;
      
      // 检查是否滚动到底部
      if (scrollHeight - scrollTop - clientHeight < 5) {
        // 到达底部，尝试加载下一页
        this.loadNextPage();
      }
    },
    
    loadNextPage() {
      // 如果不是最后一页，则加载下一页
      if (this.currentPageNum < this.totalPages) {
        this.isScrolling = true;
        this.currentPageNum++;
        
        // 在短暂延迟后重置滚动状态
        setTimeout(() => {
          this.isScrolling = false;
        }, 100);
      }
    },
    
    prevPage() {
      if (this.currentPageNum > 1) {
        this.currentPageNum--;
      }
    },
    
    nextPage() {
      if (this.totalPages > 0 && this.currentPageNum < this.totalPages) {
        this.currentPageNum++;
      }
    },
    
    zoomIn() {
      this.zoom = Math.min(this.zoom + 0.1, 3); // 限制最大缩放到300%
    },
    
    zoomOut() {
      this.zoom = Math.max(this.zoom - 0.1, 0.5); // 限制最小缩放到50%
    },
    
    closePdfViewer() {
      console.log('关闭PDF查看器');
      this.selectedPdf = null;
      this.currentPageNum = 1;
      this.totalPages = 0;
      this.zoom = 1;
      this.pdfSource = null;
      this.downloadProgressVisible = false;
      this.isScrolling = false;
    },
    
    async downloadPdf(pdf) {
      console.log('下载PDF文件:', pdf);
      try {
        // 显示下载进度条
        this.downloadProgress = 0;
        this.downloadProgressVisible = true;
        this.downloadStatus = null;
        this.downloadingPdf = pdf;
        
        const pdfUrl = `/wow/pdf/download/${pdf.id}`;
        const accessToken = localStorage.getItem('accessToken');
        
        // 使用带进度的fetch下载文件
        const response = await this.fetchWithProgress(pdfUrl, {
          headers: {
            'access-token': accessToken
          }
        });
        
        if (!response.ok) {
          throw new Error('下载PDF文件失败');
        }
        
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = pdf.fileName;
        link.click();
        window.URL.revokeObjectURL(url);
        
        this.$message.success('文件下载成功');
        // 隐藏下载进度条
        this.downloadProgressVisible = false;
      } catch (error) {
        console.error('下载PDF文件失败:', error);
        this.$message.error('下载PDF文件失败: ' + (error.message || '未知错误'));
        // 隐藏下载进度条
        this.downloadProgressVisible = false;
      }
    },
    
    handleSizeChange(newSize) {
      console.log('改变页面大小:', newSize);
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchPdfList();
    },
    
    handleCurrentChange(newPage) {
      console.log('改变当前页面:', newPage);
      this.currentPage = newPage;
      this.fetchPdfList();
    },
    
    formatFileSize(size) {
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB';
      } else {
        return (size / (1024 * 1024)).toFixed(2) + ' MB';
      }
    },
    
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN');
    }
  }
};
</script>

<style scoped>
.pdf-viewer-container {
  margin: 20px;
}

.pdf-list-section {
  margin-bottom: 20px;
}

.progress-section {
  margin-bottom: 20px;
}

.pdf-viewer-section {
  margin-top: 20px;
}

.pdf-toolbar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-info {
  margin: 0 10px;
}

.pdf-container {
  overflow: auto;
  text-align: center;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-height: 500px;
  max-height: 90vh;
  height: 85vh;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.selected-row {
  background-color: #f0f9ff;
}
</style>